<?php
/**
 * Created by PhpStorm.
 * User: zsf
 * Date: 2018/5/14
 * Time: 9:39
 */

namespace App\Services\Authorize;

use App\Services\ResponseCode;
use App\Models\{
    User\User, Enterprise\Enterprise, Enterprise\SuperEnterprise
};
use App\Services\Setting;
use Symfony\Component\HttpFoundation\File\UploadedFile;
use Illuminate\Support\Str;

class Signature extends BaseSignature implements AuthorizeInterface
{

    const SIGNATURE_HEADER_KEYS = ['username', 'timestamp', 'source', 'auth-type', 'nonce'];
    /**
     * @var $superEnterprise SuperEnterprise
     * @var $user User
     */
    protected $superEnterprise, $user, $username, $domain;

    /**
     * @return SuperEnterprise|null
     * @throws \App\Exceptions\ApiException
     * 获取当前用户
     */
    public function getUser(): ?User
    {
        $methods = get_class_methods($this);
        foreach ($methods as $method) {
            if (starts_with($method, '_validate')) {
                $this->$method();
            }
        }
        $this->verifyCaptcha();
        //私有化部署
        if(!is_ip($this->domain)){

            $this->superEnterprise = SuperEnterprise::where('domain', $this->domain)->first();
            //如果根据域名未获取到超级企业，则显示非法二级域名登录时报错
            $systemDomain = setting('system_sub_domain') . '.' . setting('primary_domain');

            if (!$this->superEnterprise && $this->domain <> $systemDomain) {
                api_exception(ResponseCode::VALID_DOMAIN);
            }

        }else{

            $this->domain = get_ip_port();
            $this->superEnterprise = SuperEnterprise::where('domain', $this->domain)->first();
            $systemDomain =  setting('primary_domain').':'.setting('system_sub_domain');

            if (!$this->superEnterprise && $this->domain <> $systemDomain) {
                api_exception(ResponseCode::VALID_DOMAIN);
            }

        }


        $seid = $this->superEnterprise ? $this->superEnterprise['id'] : 0;
        $this->user = User::where('username', $this->username)->where('seid', $seid)->first();
        if (!$this->user) {
            api_exception(ResponseCode::LOGIN_FAILED, '账号或密码错误');
        }
        if (!$this->user->is_email_verified) {
            api_exception(ResponseCode::USER_EMAIL_NOT_VERIFIED);
        }

        if ($this->validateSignature()) {
            return $this->user;
        }
        return null;
    }

    /**
     * @throws \App\Exceptions\ApiException
     * 校验用户名是否符合格式
     */
    protected function _validateUsername(): void
    {
        if (!request()->header('username') || !Str::contains(request()->header('username'), '@')) {
            api_exception(ResponseCode::USERNAME_ERROR);
        }
        $array = explode('@', request()->header('username'));
        $this->domain = $array[count($array) - 1];
        unset($array[count($array) - 1]);
        $this->username = implode('@', $array);
        if (!$this->username || !$this->domain) {
            api_exception(ResponseCode::USERNAME_ERROR);
        }
    }

    protected function getSignatureHeadKeys(): array
    {
        return self::SIGNATURE_HEADER_KEYS;
    }

    /**
     * 获取签名密钥
     * @return mixed
     */
    protected function getSignatureKey(): ?string
    {
        return $this->user['password'];
    }


}
